package com.paipaideli.ui.product;


import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.support.v7.widget.AppCompatImageView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.BuildConfig;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.utils.ImageUtil;
import com.paipaideli.common.utils.StatusBarUtil;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.common.utils.preferrnces.FastData;
import com.paipaideli.ui.MainActivity;
import com.paipaideli.ui.WelcomeActivity;
import com.paipaideli.ui.login.LoginActivity;
import com.paipaideli.ui.mine.safety.event.LogoutEvent;
import com.paipaideli.ui.price.PriceActivity;
import com.paipaideli.ui.product.view.ProWebView;
import com.paipaideli.ui.webView.WebAcyivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

/**
 * Created by 商品详情
 */
public class ProductDetailActivity extends BasePresenterActivity {

    Unbinder unbinder;

    @BindView(R.id.webview)
    ProWebView webview;
    @BindView(R.id.btn_into_price)
    Button btnIntoPrice;
    @BindView(R.id.rel_detail_profit)
    RelativeLayout relDetailProfit;
    @BindView(R.id.rel_detail_my)
    RelativeLayout relDetailMy;
    @BindView(R.id.banner_detail)
    AppCompatImageView bannerDetail;
    @BindView(R.id.image_detail_back)
    ImageView imageDetailBack;
    @BindView(R.id.tv_detail_goodname)
    TextView tvDetailGoodname;
    @BindView(R.id.tv_detail_goodprice)
    TextView tvDetailGoodprice;
    @BindView(R.id.tv_detail_scprice)
    TextView tvDetailScprice;
    @BindView(R.id.tv_detail_fdprice)
    TextView tvDetailFdprice;
    @BindView(R.id.tv_detail_oneprice)
    TextView tvDetailOneprice;
    @BindView(R.id.lin_detail_price)
    LinearLayout linDetailPrice;
    @BindView(R.id.lin_product_bottom)
    LinearLayout lin_product_bottom;
    @BindView(R.id.rel_detail_other)
    RelativeLayout relDetailOther;
    @BindView(R.id.tv_detail_pp)
    TextView tvDetailPp;
    @BindView(R.id.tv_detail_gys)
    TextView tvDetailGys;
    @BindView(R.id.rel_detail_jpgz)
    RelativeLayout relDetailJpgz;

    private String goodId;
    private String which;
    private long startTime;
    private long endTime;

    private String goodImage;
    private String description;
    private String goodName;
    private String qpPrice;
    private String scPrice;
    private String onePrice;
    private String fdPrice;


    public static void open(Context mContext, String goodId, String which) {
        Intent intent = new Intent(mContext, ProductDetailActivity.class);
        intent.putExtra("productGoodsId", goodId);
        intent.putExtra("which", which);
        mContext.startActivity(intent);
    }


    @Override
    public int getContentView() {
        return R.layout.activity_productdetail;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);

        StatusBarUtil.setStatusBarFullTransparent(ProductDetailActivity.this);
        StatusBarUtil.setFitSystemWindow(false, ProductDetailActivity.this);
        goodId = getIntent().getStringExtra("productGoodsId");
        which = getIntent().getStringExtra("which");

        //返回
        imageDetailBack.setOnClickListener(o ->
                finish()
        );

        //进入拍场
        RxView.clicks(btnIntoPrice)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
            if (FastData.isLogin()) {
                Intent intent = new Intent(ProductDetailActivity.this, PriceActivity.class);
                intent.putExtra("goodId", goodId);
                intent.putExtra("startTime", startTime);
                intent.putExtra("endTime", endTime);
                //未开始商品所需数据
                intent.putExtra("goodImage", goodImage);
                intent.putExtra("goodName", goodName);
                intent.putExtra("qpPrice", qpPrice);
                intent.putExtra("scPrice", scPrice);
                intent.putExtra("onePrice", onePrice);
                intent.putExtra("fdPrice", fdPrice);

                startActivity(intent);
            } else {
                LoginActivity.open(getCurrentActivity());
            }
        }, throwable -> {
        });

        //进入收益
        RxView.clicks(relDetailProfit).subscribe(o -> {
            LogoutEvent logoutEvent = new LogoutEvent();
            logoutEvent.setCheck(2);
            EventBus.getDefault().post(logoutEvent);
            finish();
        }, throwable -> {
        });

        //进入我的
        RxView.clicks(relDetailMy).subscribe(o -> {
            LogoutEvent logoutEvent = new LogoutEvent();
            logoutEvent.setCheck(3);
            EventBus.getDefault().post(logoutEvent);
            finish();
        }, throwable -> {
        });

        //点击查看其他网站
        RxView.clicks(relDetailOther).subscribe(o -> {
            WebAcyivity.open(getCurrentActivity(), websitUrl, "其他电商网址");
        }, throwable -> {
        });

        //竞拍规则
        RxView.clicks(relDetailJpgz).subscribe(o -> {
            WebAcyivity.open(getCurrentActivity(), BuildConfig.h5 + "auction.html", "竞拍规则");
        }, throwable -> {
        });

    }

    String websitUrl;

    @Override
    protected void onStart() {
        super.onStart();

        initDate();//初始化数据
    }

    private void initDate() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("id", goodId);
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().detail(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.code.equals("200")) {
                        if (which.equals("1")){
                            linDetailPrice.setVisibility(View.VISIBLE);
                            lin_product_bottom.setVisibility(View.VISIBLE);
                        }else {
                            linDetailPrice.setVisibility(View.GONE);
                            lin_product_bottom.setVisibility(View.GONE);
                        }
                        goodImage = request.data.coverImgPath;
                        goodName = request.data.goodsName;
                        qpPrice = request.data.goodsStartingPrice;
                        scPrice = request.data.goodsMarketPrice;
                        onePrice = request.data.goodsPriceIncreaseRange;
                        fdPrice = request.data.goodsCappedPrice;
                        ImageUtil.displayImage(goodImage, bannerDetail);
                        tvDetailGoodname.setText(goodName);
                        tvDetailGoodprice.setText("￥" + qpPrice);
                        tvDetailScprice.setText("市场价：￥" + scPrice);
                        tvDetailFdprice.setText("成交价不高于：￥" + fdPrice);
                        tvDetailOneprice.setText("加价幅度：" + onePrice);
                        tvDetailPp.setText(request.data.brandName);
                        tvDetailGys.setText(request.data.supplierName);
                        startTime = request.data.startTime;
                        description = request.data.description; //web url
                        endTime = request.data.endTime;
                        websitUrl = request.data.websiteUrl;
                        relDetailOther.setVisibility(TextUtils.isEmpty(request.data.websiteUrl) ? View.GONE : VISIBLE);
                        inHeadWebview(description);
                    } else {
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    Log.e(TAG, "error", throwable);
                });
    }

    //webview加载
    private void inHeadWebview(String description) {
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                if (!TextUtils.isEmpty(resultshop.getPicDetail())) {
//                    String s = resultshop.getPicDetail().replace("\\n", "<br/>");
//                    String str = new Gson().toJson(s);
//                    view.loadUrl("javascript:json(" + str.replaceAll("http://", "https://") + ")");
//
//                }
//                view.loadUrl("http://www.baidu.com");
            }
        });
//        webview.setVisibility(TextUtils.isEmpty(resultshop.getPicDetail()) ? GONE : VISIBLE);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);//开启硬件加速
        webview.getSettings().setBlockNetworkImage(false);//解决图片不显示
        webview.getSettings().setBuiltInZoomControls(false);
        String s = new ProductDetailTranslate().wrapperHtml(description);
        Log.i("TAG", s);
        webview.loadDataWithBaseURL(null, s, "text/html", "utf-8", null);


    }
}
